var gulp = require('gulp');
var del = require('del');
var less = require('gulp-less');
var connect = require('gulp-connect');
var mincss = require('gulp-clean-css');
var autoprefixer = require('gulp-autoprefixer');
//错误处理
var plumber = require('gulp-plumber');
var notify = require("gulp-notify");
//压缩js
var uglify = require('gulp-uglify');
// 压缩图片
var imagesmin = require('gulp-imagemin');

//src
var src = {
    html: 'src/**/*.html',
    less: 'src/less/**/*.less',
    css: 'src/less/**/*.css',
    script: 'src/script/**/*.js',
    images: 'src/images/**/*.*',
    lib: 'src/lib/**/*.*'
};
// build
var build = {
    css: 'build/css',
    js: 'build/js',
    img: 'build/img',
    lib: 'build/lib',
    path: 'build'
}

// del
gulp.task('del', function () {
    return del('build/*', {
        read: false
    })
})

//服务器
gulp.task('connect', function () {
    connect.server({
        root: build.path,
        port: 8080,
        livereload: true
    })
});

// html
gulp.task('html', function () {
    gulp.src(src.html)
        .pipe(gulp.dest(build.path))
        .pipe(connect.reload());
});

// less
gulp.task('less', function () {
    gulp.src(src.less)
        .pipe(less())
        .pipe(plumber({
            errorHandler: notify.onError("Error: <%= error.message %>")
        }))
        .pipe(autoprefixer())
        .pipe(mincss())
        .pipe(gulp.dest(build.css))
        .pipe(connect.reload())
});

// js
gulp.task('js', function () {
    gulp.src(src.script)
        .pipe(uglify())
        .pipe(gulp.dest(build.js))
        .pipe(connect.reload())
});

// img
gulp.task('img', function () {
    gulp.src(src.images)
        .pipe(imagesmin())
        .pipe(gulp.dest(build.img))
        .pipe(connect.reload())
});

// lib
gulp.task('lib', function () {
    gulp.src(src.lib)
        .pipe(gulp.dest(build.lib))
        .pipe(connect.reload())
})

gulp.task('watch', function () {
    gulp.watch([src.html], ['html']);
    gulp.watch([src.less], ['less']);
    gulp.watch([src.script], ['js']);
    gulp.watch([src.images], ['img']);
    gulp.watch([src.lib], ['lib']);
})

gulp.task('default', ['del'], function () {
    gulp.start(['html', 'less', 'js', 'img', 'lib', 'connect', 'watch'])
});